 <?php
 //airplort
	$TARGETBRANCH = '邮件里的Target Branch|目标航线？';
	$CREDENTIALS = 'Universal API/API1234567:Password|邮件里的密码';
	$Provider = 'ACH'; //provider 供应商1G/1P/1V/ACH 
/*
Web Services and Schema
SOAP Web Services

Providers
Galileo (1G)
Worldspan (1P)
Apollo (1V)
Axess (1J)
Airline Content Hub (ACH)
Rail Content Hub (RCH)
Travelport Rooms and More (TRM)

ACH Carriers
a session timeout limit of 1 hour.
ACH carriers session周期更短

(单个请求无法预定多个航班|旅馆|)More than one hotel or vehicle segment cannot be booked in a single Universal API request. 
If more than one hotel or vehicle segment is needed, the customer can choose to: 
（|现有的PNR）Add the segment to an existing Universal Record and existing PNR.
（|创建新的PNR）Create a new PNR and add it to the existing Universal Record.

a Universal Record with Multiple PNRs

转化
Montreal and Vancouver往返程
出境航班预定Carrier A through the Galileo GDS. 
入境航班预定Carrier B through ACH. 
通过AirCreateReservationReq call 预定的机票, 
生成 an aggregated 1G/ACH request.
响应生成|返回包含以下两个PNR数据的Universal Record 123456 .  
Galileo ABCDEF, （存储出境航班）  
ACH UVWXYZ, （存储入境航班）.
*/
	
/*
	AvailabilitySearchReq	
	BillingPointOfSaleInfo OriginApplication
	SearchAirLeg
		SearchOrigin
		SearchDestination
		SearchDepTime
	AirSearchModifiers
		PreferredProviders
	
	<AirSegment Key="1" Group="0" Carrier="AS" FlightNumber="563" Origin="SFO" Destination="SEA"

DepartureTime="2009-06-02T09:00:00.000-07:00"

ArrivalTime="2009-06-02T11:10:00.000-07:00"

ClassOfService="V" ETicketability="Yes" Status="HK"\>	
		
Credentials加密方式|密码验证


请求：
http头部HTTP header 
soap（包含被请求的服务器，gzip状态，密码，xml请求||所有的都需要tls加密）|a SOAP envelope
gzip status

POST https://americas.universal-api.pp.travelport.com/
B2BGateway/connect/uAPI/HotelService HTTP/2.0       

Accept-Encoding: gzip,deflate

Content-Type: text/xml;charset=UTF-8

SOAPAction: ""

Authorization: Basic UniversalAPI/UserName:Password

Content-Length: length
		
*/
$message = <<<EOM
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Header/>
   <soapenv:Body>
      <air:AvailabilitySearchReq TraceId="trace" AuthorizedBy="user" TargetBranch="$TARGETBRANCH" xmlns:air="http://www.travelport.com/schema/air_v29_0" xmlns:com="http://www.travelport.com/schema/common_v29_0">
         <com:BillingPointOfSaleInfo OriginApplication="UAPI"/>
         <air:SearchAirLeg>
            <air:SearchOrigin>
               <com:Airport Code="LGW"/>
            </air:SearchOrigin>
            <air:SearchDestination>
               <com:Airport Code="EDI"/>
            </air:SearchDestination>
            <air:SearchDepTime PreferredTime="2014-12-31">
            </air:SearchDepTime>            
         </air:SearchAirLeg>
         <air:AirSearchModifiers>
            <air:PreferredProviders>
               <com:Provider Code="$Provider"/>
            </air:PreferredProviders>
         </air:AirSearchModifiers>
      </air:AvailabilitySearchReq>
   </soapenv:Body>
</soapenv:Envelope>
EOM;

	$file = "001-".$Provider."_AirAvailabilityReq.xml"; //发起的请求的xml文件for test only 
	prettyPrint($message,$file);//格式化xml 
	$auth = base64_encode("$CREDENTIALS"); //密码加密
	$soap_do = curl_init ("https://americas.universal-api.pp.travelport.com/B2BGateway/connect/uAPI/AirService");
	$header = array(
	"Content-Type: text/xml;charset=UTF-8", 
	"Accept: gzip,deflate", 
	"Cache-Control: no-cache", 
	"Pragma: no-cache", 
	"SOAPAction: \"\"",
	"Authorization: Basic $auth", //转义后的密码
	"Content-length: ".strlen($message),
	); 
	//curl_setopt($soap_do, CURLOPT_CONNECTTIMEOUT, 30); 
	//curl_setopt($soap_do, CURLOPT_TIMEOUT, 30); 
	curl_setopt($soap_do, CURLOPT_SSL_VERIFYPEER, false); 
	curl_setopt($soap_do, CURLOPT_SSL_VERIFYHOST, false); 
	curl_setopt($soap_do, CURLOPT_POST, true ); 
	curl_setopt($soap_do, CURLOPT_POSTFIELDS, $message); 
	curl_setopt($soap_do, CURLOPT_HTTPHEADER, $header);
	curl_setopt($soap_do, CURLOPT_RETURNTRANSFER, true); // 禁止curl_exec 返回结果|以捕获输出 this will prevent the curl_exec to return result and will let us to capture output
	$return = curl_exec($soap_do); 
	$file = "001-".$Provider."_AirAvailabilityRsp.xml"; // 返回的响应的xml文件for test only 
	$content = prettyPrint($return,$file);
	parseOutput($content);
	//print '<br>';
	//echo $return;
	//print '<br>';
	//print_r(curl_getinfo($soap_do));

	//格式化xml Pretty print XML
	function prettyPrint($result,$file){
		$dom = new DOMDocument;
		$dom->preserveWhiteSpace = false;
		$dom->loadXML($result);
		$dom->formatOutput = true;		
		//call function to write request/response in file	
		outputWriter($file,$dom->saveXML());
		return $dom->saveXML();
	}

	//将结果输出到文件function to write output in a file
	function outputWriter($file,$content){	
		file_put_contents($file, $content); // Write request/response and save them in the File
	}

	function parseOutput($content){	//parse the Search response to get values to use in detail request
		$AirAvailabilitySearchRsp = $content; //use this if response is not saved anywhere else use above variable
		//echo $AirAvailabilitySearchRsp;
		$xml = simplexml_load_String("$AirAvailabilitySearchRsp", null, null, 'SOAP', true);	
		
		if($xml)
			echo "Processing! Please wait!";
		else{
			trigger_error("Encoding Error!", E_USER_ERROR);
		}

		$Results = $xml->children('SOAP',true);
		foreach($Results->children('SOAP',true) as $fault){
			if(strcmp($fault->getName(),'Fault') == 0){
				trigger_error("Error occurred request/response processing!", E_USER_ERROR);
			}
		}
		
		$count = 0;
		$fileName = "flights.txt";
		if(file_exists($fileName)){
			file_put_contents($fileName, "");
		}
		foreach($Results->children('air',true) as $nodes){
			foreach($nodes->children('air',true) as $hsr){
				if(strcmp($hsr->getName(),'AirSegmentList') == 0){
					foreach($hsr->children('air',true) as $hp){
						if(strcmp($hp->getName(),'AirSegment') == 0){
							$count = $count + 1;
							file_put_contents($fileName,"\r\n"."Air Segment ".$count."\r\n"."\r\n", FILE_APPEND);
							foreach($hp->attributes() as $a => $b	){
									$GLOBALS[$a] = "$b";
									//echo "$a"." : "."$b";
									file_put_contents($fileName,$a." : ".$b."\r\n", FILE_APPEND);
							}												
						}					
					}
				}
				//break;
			}
		}
		$Token = 'Token';
		$TokenKey = 'TokenKey';
		$fileName = "tokens.txt";
		if(file_exists($fileName)){
			file_put_contents($fileName, "");
		}
		foreach($Results->children('air',true) as $nodes){
			foreach($nodes->children('air',true) as $hsr){
				if(strcmp($hsr->getName(),'HostTokenList') == 0){			
					foreach($hsr->children('common_v29_0', true) as $ht){
						if(strcmp($ht->getName(), 'HostToken') == 0){
							$GLOBALS[$Token] = $ht[0];
							foreach($ht->attributes() as $a => $b){
								if(strcmp($a, 'Key') == 0){
									file_put_contents($fileName,$TokenKey.":".$b."\r\n", FILE_APPEND);
								}
							}						
							file_put_contents($fileName,$Token.":".$ht[0]."\r\n", FILE_APPEND);
						}
					}
				}
			}
		}
		
		echo "\r\n"."Processing Done. Please check results in files.";

	}
